package com.paradise.ytj.fragment;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.paradise.ytj.R;
import com.paradise.ytj.activity.MainActivity;
import com.paradise.ytj.activity.VideoActivity;
import com.paradise.ytj.bean.ContactInfo;
import com.paradise.ytj.helper.ContactDao;
import com.paradise.ytj.helper.RecordDao;
import com.paradise.ytj.utils.CameraUtils;
import com.paradise.ytj.utils.DialogUtils;
import com.paradise.ytj.view.CustomDialog;

import java.util.Date;
import java.util.List;

public class ContactFragment extends Fragment implements View.OnClickListener, View.OnFocusChangeListener {
    private View inflate;
    private ListView lvFragmentAddressContact;
    private ContactDao contactDao;
    private ContactAdapter cAdapter;
    private ImageView ivDelete;
    private ImageView ivAddContact;
    private EditText etSearch;
    private List<ContactInfo> contactInfos;
    private ListView lvFind;
    private TextView tvAddContact;
    private LinearLayout llNotData;
    private ContactAdapter adapter;
    private Activity context;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        context = getActivity();
        inflate = View.inflate(context, R.layout.fragment_contact, null);
        initView();
        initData();
        initListener();
        return inflate;
    }

    /**
     * 初始化控件
     */
    private void initView() {
        lvFragmentAddressContact = (ListView) inflate.findViewById(R.id.lv_fragment_address_contact);
        lvFind = (ListView) inflate.findViewById(R.id.lv_fragment_address_find);
        ivDelete = (ImageView) inflate.findViewById(R.id.iv_delete);
        llNotData = (LinearLayout) inflate.findViewById(R.id.ll_not_data);
        ivAddContact = (ImageView) inflate.findViewById(R.id.iv_clear_record);
        etSearch = (EditText) inflate.findViewById(R.id.et_contact_search);
        tvAddContact = (TextView) inflate.findViewById(R.id.tv_clear_record);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        contactDao = new ContactDao(context);
        final List<ContactInfo> contactInfos = contactDao.getAllContacts();
        cAdapter = new ContactAdapter(contactInfos);
        lvFragmentAddressContact.setAdapter(cAdapter);
        lvFragmentAddressContact.setItemsCanFocus(true);
        lvFind.setItemsCanFocus(true);
        if (contactInfos.size() > 0) {
            lvFragmentAddressContact.setVisibility(View.VISIBLE);
            llNotData.setVisibility(View.INVISIBLE);
        } else {
            lvFragmentAddressContact.setVisibility(View.INVISIBLE);
            llNotData.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 初始化事件
     */
    private void initListener() {
        etSearch.setOnClickListener(this);
        ivDelete.setOnClickListener(this);
        ivAddContact.setOnClickListener(this);
        ivAddContact.setOnFocusChangeListener(this);
        ivDelete.setOnFocusChangeListener(this);
        etSearch.setOnFocusChangeListener(this);
        etSearch.addTextChangedListener(new ContactWatcher());
        etSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                lvFragmentAddressContact.setSelection(0);
                lvFind.setSelection(0);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_delete:
                String search = etSearch.getText().toString();
                if (search.length() > 0) {
                    search = search.substring(0, search.length() - 1);
                    etSearch.setText(search);
                }
                break;

            case R.id.iv_clear_record:

                final CustomDialog customDialog = new CustomDialog(context);
                if (!getActivity().isFinishing()) {
                    customDialog.show();
                }
                View inflate = View.inflate(context, R.layout.dialog_add_contact, null);
                final EditText etContactName = (EditText) inflate.findViewById(R.id.et_contact_name);
                final EditText etContactAccount = (EditText) inflate.findViewById(R.id.et_contact_account);
                ImageView ivDeleteAccount = (ImageView) inflate.findViewById(R.id.iv_delete_account);
                ImageView ivDeleteName = (ImageView) inflate.findViewById(R.id.iv_delete_name);

                customDialog.setTitleText(R.string.add_contact);
                customDialog.getContentView().addView(inflate);
                customDialog.setOnSubmitListener(new CustomDialog.OnSubmitListener() {
                    @Override
                    public void onSubmitClick() {
                        String account = etContactAccount.getText().toString().trim();
                        if (TextUtils.isEmpty(account)) {
                            return;
                        }

                        String name = etContactName.getText().toString().trim();
                        if (TextUtils.isEmpty(name)) {
                            return;
                        }

                        ContactDao dao = new ContactDao(context);
                        if (dao.findByAccount(account)) {
                            Toast.makeText(context, R.string.exist_account, Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (dao.add(name, account)) {
                            customDialog.dismiss();
                            etContactAccount.setText("");
                            etContactName.setText("");
                            Toast.makeText(context, R.string.add_success, Toast.LENGTH_SHORT).show();
                            contactInfos = contactDao.getAllContacts();
                            cAdapter = new ContactAdapter(contactInfos);
                            lvFragmentAddressContact.setAdapter(cAdapter);
                            if (contactInfos.size() > 0) {
                                lvFragmentAddressContact.setVisibility(View.VISIBLE);
                                llNotData.setVisibility(View.INVISIBLE);
                            } else {
                                lvFragmentAddressContact.setVisibility(View.INVISIBLE);
                                llNotData.setVisibility(View.VISIBLE);
                            }
                        } else {
                            Toast.makeText(context, R.string.add_fail, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                customDialog.setOnCancelListener(new CustomDialog.OnCancelListener() {
                    @Override
                    public void onCancelClick() {
                        customDialog.dismiss();

                    }
                });
                etContactAccount.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        etContactAccount.setInputType(InputType.TYPE_CLASS_TEXT);
                        etContactAccount.requestFocus();
                        InputMethodManager imm = (InputMethodManager) etContactAccount.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(etContactAccount, 0);
                    }
                });
                etContactName.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        etContactName.setInputType(InputType.TYPE_CLASS_TEXT);
                        etContactName.requestFocus();
                        InputMethodManager imm = (InputMethodManager) etContactName.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(etContactName, 0);
                    }
                });
                ivDeleteAccount.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (etContactAccount.getText().toString().length() > 0) {
                            etContactAccount.setText(etContactAccount.getText().toString().substring(0, etContactAccount.getText().length() - 1));
                        }
                    }
                });

                ivDeleteName.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (etContactName.getText().toString().length() > 0) {
                            etContactName.setText(etContactName.getText().toString().substring(0, etContactName.getText().length() - 1));
                        }
                    }
                });
                break;
            case R.id.et_contact_search:
                etSearch.setInputType(InputType.TYPE_CLASS_TEXT);
                etSearch.requestFocus();
                InputMethodManager immm = (InputMethodManager) etSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                immm.showSoftInput(etSearch, 0);
                break;
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.iv_clear_record:
                if (hasFocus) {
                    tvAddContact.setTextColor(context.getResources().getColor((R.color.add)));
                } else {
                    tvAddContact.setTextColor(context.getResources().getColor((R.color.gray)));
                }
                break;
        }
    }

    class ContactWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.toString().length() == 0) {
                contactInfos = contactDao.getAllContacts();
                cAdapter = new ContactAdapter(contactInfos);
                lvFragmentAddressContact.setAdapter(cAdapter);
                lvFragmentAddressContact.setVisibility(View.VISIBLE);
                lvFind.setVisibility(View.INVISIBLE);
            } else {
                lvFragmentAddressContact.setVisibility(View.INVISIBLE);
                lvFind.setVisibility(View.VISIBLE);
            }

        }

        @Override
        public void afterTextChanged(Editable s) {
            String text = s.toString();
            List<ContactInfo> findInfos = contactDao.findByText(text);
            adapter = new ContactAdapter(findInfos);
            lvFind.setAdapter(adapter);
        }
    }


    class ContactAdapter extends BaseAdapter implements View.OnFocusChangeListener {

        private List<ContactInfo> contacts;

        public ContactAdapter(List<ContactInfo> contactInfos) {
            this.contacts = contactInfos;
        }

        @Override
        public int getCount() {
            return contacts.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.contact_item, null);
                holder = new ViewHolder();
                holder.tvAccount = (TextView) convertView.findViewById(R.id.tv_contact_account);
                holder.tvName = (TextView) convertView.findViewById(R.id.tv_contact_name);
                holder.ivDelete = (ImageView) convertView.findViewById(R.id.iv_contact_delete);
                holder.ivEdit = (ImageView) convertView.findViewById(R.id.iv_contact_edit);
                holder.llContact = (LinearLayout) convertView.findViewById(R.id.ll_contact);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (position == contacts.size() - 1) {
                holder.llContact.setNextFocusDownId(R.id.rb_contact);
                holder.ivDelete.setNextFocusDownId(R.id.rb_contact);
                holder.ivEdit.setNextFocusDownId(R.id.rb_contact);
            }
            holder.tvAccount.setText(contacts.get(position).getNumber());
            holder.tvName.setText(contacts.get(position).getName());
            holder.ivDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    contactDao.delete(contacts.get(position).getNumber());
                    if (!TextUtils.isEmpty(etSearch.getText().toString())) {
                        contacts.remove(position);
                        adapter.notifyDataSetChanged();
                    } else {
                        contacts = contactDao.getAllContacts();
                        cAdapter.notifyDataSetChanged();
                        if (contacts.size() > 0) {
                            lvFragmentAddressContact.setVisibility(View.VISIBLE);
                            llNotData.setVisibility(View.INVISIBLE);
                        } else {
                            lvFragmentAddressContact.setVisibility(View.INVISIBLE);
                            llNotData.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
            holder.llContact.setOnFocusChangeListener(this);
            holder.ivEdit.setOnFocusChangeListener(this);
            holder.ivDelete.setOnFocusChangeListener(this);
            holder.llContact.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!MainActivity.isOnLine) {
                        Toast.makeText(context, R.string.offline_hint, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (CameraUtils.getNumber() == 0) {
                        Toast.makeText(context, R.string.no_camera_hint, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    ContactDao contactDao = new ContactDao(context);
                    String name = contactDao.getNameByAccount(contacts.get(position).getNumber());
                    if (name.equals("未知联系人")) {
                        name = contactInfos.get(position).getNumber();
                    }
                    Intent intent = new Intent(context, VideoActivity.class);
                    intent.putExtra("inout", "out");
                    intent.putExtra("object", name);
                    intent.putExtra("phone", contacts.get(position).getNumber());
                    startActivity(intent);
                }
            });
            holder.ivEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final CustomDialog customDialog = new CustomDialog(context);
                    if (!getActivity().isFinishing()) {
                        customDialog.show();
                    }
                    View inflateEdit = View.inflate(context, R.layout.dialog_add_contact, null);
                    final EditText etName = (EditText) inflateEdit.findViewById(R.id.et_contact_name);
                    final EditText etAccount = (EditText) inflateEdit.findViewById(R.id.et_contact_account);
                    ImageView ivDeleteAccount = (ImageView) inflateEdit.findViewById(R.id.iv_delete_account);
                    ImageView ivDeleteName = (ImageView) inflateEdit.findViewById(R.id.iv_delete_name);

                    customDialog.setTitleText(R.string.add_contact);
                    customDialog.getContentView().addView(inflateEdit);

                    etAccount.setText(contacts.get(position).getNumber());
                    etName.setText(contacts.get(position).getName());
                    etAccount.setSelection(etAccount.getText().length());
                    etName.setSelection(etName.getText().length());

                    customDialog.setOnSubmitListener(new CustomDialog.OnSubmitListener() {
                        @Override
                        public void onSubmitClick() {
                            String account = etAccount.getText().toString().trim();
                            if (TextUtils.isEmpty(account)) {
                                Toast.makeText(context, R.string.account_hint, Toast.LENGTH_SHORT).show();
                                return;
                            }

                            String name = etName.getText().toString().trim();
                            if (TextUtils.isEmpty(name)) {
                                Toast.makeText(context, R.string.name_hint, Toast.LENGTH_SHORT).show();
                                return;
                            }

                            if (contactDao.update(contacts.get(position).getNumber(), name, account)) {
                                etAccount.setText("");
                                etName.setText("");
                                customDialog.dismiss();
                                Toast.makeText(context, R.string.operation_success, Toast.LENGTH_SHORT).show();
                                contacts = contactDao.getAllContacts();
                                cAdapter.notifyDataSetChanged();
                            } else {
                                Toast.makeText(context, R.string.operation_fail, Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    customDialog.setOnCancelListener(new CustomDialog.OnCancelListener() {
                        @Override
                        public void onCancelClick() {
                            customDialog.dismiss();

                        }
                    });

                    etAccount.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            etAccount.setInputType(InputType.TYPE_CLASS_TEXT);
                            etAccount.requestFocus();
                            InputMethodManager imm = (InputMethodManager) etAccount.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.showSoftInput(etAccount, 0);
                        }
                    });

                    etName.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            etName.setInputType(InputType.TYPE_CLASS_TEXT);
                            etName.requestFocus();
                            InputMethodManager imm = (InputMethodManager) etName.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.showSoftInput(etName, 0);
                        }
                    });

                    ivDeleteAccount.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (etAccount.getText().toString().length() > 0) {
                                etAccount.setText(etAccount.getText().toString().substring(0, etAccount.getText().length() - 1));
                            }
                        }
                    });

                    ivDeleteName.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (etName.getText().toString().length() > 0) {
                                etName.setText(etName.getText().toString().substring(0, etName.getText().length() - 1));
                            }
                        }
                    });
                }
            });
            return convertView;
        }

        @Override
        public void onFocusChange(View v, boolean hasFocus) {

        }

        class ViewHolder {
            TextView tvName;
            TextView tvAccount;
            ImageView ivDelete;
            ImageView ivEdit;
            LinearLayout llContact;

        }
    }

}
